package com.example.studyFile.jdknewfeatures._02_CompletableFuture_allOf;


//import com.google.common.util.concurrent.ThreadFactoryBuilder;

import lombok.extern.slf4j.Slf4j;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.logging.Logger;
/**
 * 
 * @Description:TODO(CompletableFuture.allOf使用)   
 * @author: HeShengjin
 * @date:   2021年5月7日 下午4:22:51    
 * @Copyright:
 */
// @Slf4j
public class AllOfTest {
	private final static Logger log = Logger.getLogger(AllOfTest.class.getName());
	//使用自己的线程池
    private final static ThreadPoolExecutor executorServe = new ThreadPoolExecutor(3,
            Runtime.getRuntime().availableProcessors() * 3,
            5, 
            TimeUnit.MINUTES,
            new ArrayBlockingQueue<>(1000));
    //随机数
    private static Random random = new Random();

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        //现在时间
    	Instant start = Instant.now();
        
        List<CompletableFuture<String>> list = new ArrayList<CompletableFuture<String>>();
        
        list.add(CompletableFuture.supplyAsync(() -> getData(), executorServe));
        list.add(CompletableFuture.supplyAsync(() -> getData(), executorServe));
        list.add(CompletableFuture.supplyAsync(() -> getData(), executorServe));
                
        // CompletableFuture.allOf(list.toArray(new CompletableFuture[list.size()])).join();
        try {
            //list.toArray 将list转化为你所需要类型的数组，当然我们用的时候会转化为与list内容相同的类型。
            CompletableFuture.allOf(list.toArray(new CompletableFuture[list.size()])).get(10,TimeUnit.SECONDS);

        } catch (InterruptedException e) {
            log.info("线程超时抛出异常");
        }finally {
            //结束线程池（为什么一定要停止）
            //不关闭线程池的话，他会一直等待新的线程进来
            executorServe.shutdownNow();
        }

        log.info(String.format("********全部执行完毕，总耗时:%s ********", (ChronoUnit.SECONDS.between(start, Instant.now()))));
        //打印结果
        list.parallelStream().forEach((cf)->{
        	log.info(cf.join());
        });
        executorServe.shutdownNow();
    }

    /**
     * 
     * @Description: TODO(随机模拟请求耗时)   
     * @param: @return      
     * @return: String      
     * @throws
     */
    private static String getData() {
        int anInt = random.nextInt(10);
        String info = String.format("----当前线程%s,随机数：%s秒----",Thread.currentThread().getName(), anInt);
        log.info(info);
        try {
            TimeUnit.SECONDS.sleep(anInt);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "【结束返回】"+info;

    }
}



